package com.fangngng.pushall.controller;

import com.fangngng.pushall.entity.Role;
import com.fangngng.pushall.entity.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author fei.fang
 * @date 2021/1/18
 **/
public class BaseController {

    protected User getCurrentUser(){
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        String email = authentication.getName();
        Collection<GrantedAuthority> roles = authentication.getAuthorities();
        List<Role> roleList = new ArrayList<>();
        for (GrantedAuthority role : roles) {
            String name = role.getAuthority();
            Role role1 = new Role();
            role1.setName(name);
            roleList.add(role1);
        }
        User userDetail = new User();
        userDetail.setEmail(email);
        userDetail.setAuthorities(roleList);
        return userDetail;
    }
}
